package com.xw.netty.basic;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * 客户端的业务处理类
 * @ClassName NettyClientHandler
 * @Author liu zhiyong
 * @Date 2020/8/20 16:46
 * @Version 1.0
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter{

    /**
     * 通道就绪（当有新的客户端连接服务器之后，会自动调用这个方法）
     * @param ctx
     * @return void
     **/
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client:" + ctx);
        ctx.writeAndFlush(Unpooled.copiedBuffer("Client->" + ctx.channel().id() + ":server, hello...", CharsetUtil.UTF_8));
    }

    /**
     * 读取数据事件
     * @param ctx
     * @param msg
     * @return void
     **/
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println(buf.toString(CharsetUtil.UTF_8));
    }
}
